﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using System.Collections;
using Microsoft.Xna.Framework.Input;
using System.IO;
using System.Globalization;
using CakeAnimation;

namespace CharacterAnimationEditor
{

    public class SkeletonView
    {
        public float Alpha = 1.0f;
        public float Scale = 1.0f;
        public float ZOffset = 1.0f;
        public Color Tint = Color.White;
        public Vector2 Offset;
        public bool HandleControlTints = false;

        public Skeleton MySkeleton { get; set; }

        public void Draw(Context context)
        {
            DrawRecursively(context, MySkeleton.RootBone);
        }

        private void DrawRecursively(Context context, Bone bone)
        {
            Draw(context, bone);

            foreach (Bone b in bone.Children)
            {
                DrawRecursively(context, b);
            }
        }

        float t = 0.0f;
        private void Draw(Context context, Bone bone)
        {

            Color c = bone.Fixed ? Color.Red : bone == context.SelectedBone ? Color.White : bone == context.HoveredBone ? Color.Silver : Color.Gray;
            c.A = bone == context.HoveredBone ? (Byte)(255 * (0.5f + 0.5f * (float)Math.Cos((double)t))) : (Byte)255;
            c.A = bone == context.SelectedBone ? (Byte)(255 * (0.85f + 0.15f * (float)Math.Cos((double)t / 2))) : c.A;

            if (bone.Filtered)
            {
                c = Color.Gray;
                c.A = 100;
            }

            if (!HandleControlTints)
            {
                c = Color.Silver;
            }

            c.A = (Byte)(c.A * Alpha);


            if (Tint != Color.White)
            {
                Byte a = c.A;
                c = Color.Lerp(c, Tint, 0.7f);
                c.A = a;
            }

            t += context.DeltaTime;

            Vector2 pos = bone.GetCenter() * Scale * context.GetWindowScale() + Offset * context.GetWindowScale();

            context.SpriteBatch.Draw(
                bone.Texture,
                pos,
                null,
                c,
                bone.Rotation,
                new Vector2(bone.Texture.Width, bone.Texture.Height) * 0.5f,
                Scale * context.GetWindowScale(),
                SpriteEffects.None,
                bone == context.HoveredBone ? 0.0f : bone.ZDepth * ZOffset
                );

            /*
            context.Sb.DrawString(
                context.Font,
                "X",
                bone.GetTip() * Scale * context.GetWindowScale() + Offset * context.GetWindowScale(),
                Color.Black);
             //*/
        }

    }

}
